package com.xyz.app.shiro;

import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.utils.HttpUtils;
import com.free.utils.enums.ENUM_DEVICE_TYPE;
import com.xyz.app.constants.ShiroConstants;
import com.xyz.domain.table.CCustomer;
import com.xyz.service.CustomerService;
import com.xyz.shiro.BasicShiroFilter;
import com.xyz.shiro.CaptchaTokenUserNameToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class UserShiroFilter extends BasicShiroFilter {

    private static final FreeLogger LOG = FreeLoggerFactory.getLogger(UserShiroFilter.class);
    private CustomerService customerService;
    private EhCacheCacheManager ehCacheCacheManager;

    public UserShiroFilter(CustomerService customerService, EhCacheCacheManager ehCacheCacheManager){
        this.customerService = customerService;
        this.ehCacheCacheManager = ehCacheCacheManager;
    }

    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String KAPTCHA = "captcha";
    private static final String TOKEN = "token";

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String userName = WebUtils.getCleanParam(servletRequest, USERNAME);
        String password = WebUtils.getCleanParam(servletRequest, PASSWORD);
        String kaptcha = WebUtils.getCleanParam(servletRequest, KAPTCHA);
        String token = WebUtils.getCleanParam(servletRequest, TOKEN);
        return new CaptchaTokenUserNameToken(kaptcha, userName, password, token);
    }

    @Override
    public void loginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) {
        ENUM_DEVICE_TYPE deviceType = HttpUtils.getDeviceType(WebUtils.toHttp(request));
        CCustomer customer = (CCustomer) subject.getPrincipal();
        String sign = this.customerService.jwtTokenSign(customer, String.valueOf(deviceType.getKey()));
        setHeader(WebUtils.toHttp(response), ShiroConstants.TOKEN_HEADER_NAME, sign);
    }

    @Override
    public void loginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

    }
}
